package fr.tm.ima.client.gxt.grid.view;

/**
 * @author aquinault
 */

import java.util.ArrayList;
import java.util.List;

import org.puremvc.java.multicore.interfaces.INotification;
import org.puremvc.java.multicore.patterns.mediator.Mediator;

import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Widget;

import fr.tm.ima.client.gxt.grid.GridFacade;

/**
 * Grid Mediator. 
 */
public class GridMediator extends Mediator {

	/**
	 * Mediator name.
	 */
	public static final String NAME = "GridMediator";
	
	/**
	 * The GXT Grid.
	 */
	Grid grid;
	
	/**
	 * Constructor.
	 */
	public GridMediator()	{
		super(NAME, null);
		initGrid();
	}
	
	/**
	 * Initialize the grid view.
	 */
	private void initGrid() {

		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
	    columns.add(new ColumnConfig("Sender", "Sender", 100));
	    columns.add(new ColumnConfig("Email", "Email", 165));
	    columns.add(new ColumnConfig("Phone", "Phone", 100));
	    columns.add(new ColumnConfig("State", "State", 50));
	    columns.add(new ColumnConfig("Zip", "Zip Code", 65));

	    // create the column model
	    final ColumnModel cm = new ColumnModel(columns);
		    
	    final ListStore<ModelData> store = new ListStore<ModelData>();
	    
	    grid = new Grid<ModelData>(store, cm);
	    grid.setBorders(true);
	    grid.setAutoExpandColumn("Sender");

	    // add button  
		Button load = new Button("Load XML");  
		load.addClickListener(new ClickListener(){

		public void onClick(Widget sender) {
			sendNotification(GridFacade.FILL_MODEL_COMMAND);
		}});
		 
		VerticalPanel vp = new VerticalPanel();
		vp.add(grid);
		vp.add(load);
	         
		this.setViewComponent(vp);
	}

	@Override
	public String[] listNotificationInterests() {
		
		return new String[]{
				GridFacade.MODEL_CHANGED
		};
	}

	@Override
	public void handleNotification(INotification notification) {
		if (notification.getName() == GridFacade.MODEL_CHANGED) {
			List<ModelData> list = (List<ModelData>)(notification.getBody());
			ListStore<ModelData> store = new ListStore<ModelData>();
			store.add(list);
			grid.getStore().add(store.getModels());
      		grid.getView().render();
		}
		super.handleNotification(notification);
	}
	
}
